package com.ykq.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ykq.system.entity.User;
import com.ykq.system.service.IUserService;
import com.ykq.system.vo.CommonResult;
import com.ykq.system.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @program: qy151-springboot-vue
 * @description:
 * @author: 闫克起2
 * @create: 2022-08-08 10:08
 **/
@RestController
@RequestMapping("/system")
@Api(tags = "登录的接口类")
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/logout")
    public CommonResult logout(HttpServletRequest request){
        String token = request.getHeader("token");
        if(redisTemplate.hasKey(token)){
            redisTemplate.delete(token);
            return new CommonResult(2000,"退出成功",null);
        }
        return new CommonResult(5000,"无效得token",null);
    }


    @PostMapping("login")
    @ApiOperation(value="登录接口")
    public CommonResult login(@RequestBody LoginVo loginVo){
         try{
             Subject subject = SecurityUtils.getSubject();
             UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginVo.getName(),loginVo.getPassword());
             subject.login(usernamePasswordToken);

             Object one = subject.getPrincipal();
             //随机生成一个唯一字符串。
            String token = UUID.randomUUID().toString();
            //把该token作为redis的key value为当前登录用户信息
            ValueOperations forValue = redisTemplate.opsForValue();
            forValue.set(token,one,24, TimeUnit.HOURS);
            return new CommonResult(2000,"登录成功",token);
        }catch (Exception e){
            return new CommonResult(5000,"登录失败",null);
        }

    }
}
